import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

import '../../../utils/util.dart';
import '../refresh/tab_refresh/view.dart';
import 'index.dart';

abstract class CasstlePage<T extends CasstleController>
    extends ITabRefreshPage<T> with SliverAppBarMixin {
  const CasstlePage({Key? key}) : super(key: key);

  @protected
  bool? get refreshOnHeaderTop => false;
  @protected
  List<Widget> buildHeaderSliver(BuildContext context, bool innerBoxIsScrolled);

  @override
  Widget buildRefreshBody(BuildContext context) {
    return const SizedBox();
  }

  Widget buildNestScrollView(BuildContext context, ScrollPhysics physics) {
    return NestedScrollView(
      physics: physics,
      headerSliverBuilder: (context, innerBoxIsScrolled) {
        final list = buildHeaderSliver(context, innerBoxIsScrolled);
        if (refreshOnHeaderTop == true) {
          list.insert(
            0,
            const HeaderLocator.sliver(clearExtent: false),
          );
        } else if (refreshOnHeaderTop == false) {
          list.add(
            const HeaderLocator.sliver(clearExtent: false),
          );
        }
        return list;
      },
      body: buildUpdateTabBarView(context, physics: physics),
    );
  }

  @override
  Widget buildRefreshView(BuildContext context) {
    return EasyRefresh.builder(
      controller: controller.state.controller,
      onRefresh: controller.onRefresh,
      onLoad: controller.state.enablePullup ? controller.onLoading : null,
      header: const MaterialHeader(
        clamping: true,
        position: IndicatorPosition.locator,
      ),
      childBuilder: (context, physics) {
        return buildNestScrollView(context, physics);
      },
    );
  }

  @override
  Widget buildView(BuildContext context, Widget refreshBody) {
    return refreshBody;
  }
}

mixin SliverAppBarMixin {
  SliverAppBar floatAppBar1(
    BuildContext context, {
    required Widget title,
    Widget? leadding,
    double? leaddingWidth,
    List<Widget>? actions,
    required Widget body,
    required double pinnedHeight,
    required Widget floatChild,
    double? floatHeight,
  }) {
    return SliverAppBar(
      title: title,
      leading: leadding,
      leadingWidth: leaddingWidth,
      centerTitle: true,
      actions: actions,
      flexibleSpace: FlexibleSpaceBar(
        background: body,
        stretchModes: const [StretchMode.fadeTitle, StretchMode.zoomBackground],
      ),
      stretch: true,
      pinned: true,
      expandedHeight: ScreenAdapter().safeTop + pinnedHeight,
      bottom: PreferredSize(
          preferredSize: Size.fromHeight(floatHeight ?? 44.r),
          child: floatChild),
    );
  }
}
